package org.lonetree.tc.webapp.actions;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.lonetree.tc.core.Book;
import org.lonetree.tc.core.Book.Isbn;
import org.lonetree.tc.core.dao.BookDAO;
import org.lonetree.tc.core.dao.DAOFactory;
import org.lonetree.tc.webapp.forms.BookForm;

public class UpdateBook extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// TODO Auto-generated method stub
		try{
			
			DAOFactory factory = DAOFactory.getDAOFactory(DAOFactory.FactoryImplementation.DB_DAO_FACTORY);
			BookDAO bdao = factory.getBookDAO();
			
			if (!request.getMethod().toLowerCase().equals("post"))
			{
				String isbn=request.getParameter("isbn");
				Book book=bdao.getBook(new Isbn(isbn));	
				
				//pre-populated form with the book information
				//retried from db
				request.setAttribute("loaded", book);
				return mapping.findForward("success_get");
			}
			
			if (request.getMethod().toLowerCase().equals("post"))
			{
				Class.forName("com.mysql.jdbc.Driver");
				Connection connection  = DriverManager.getConnection(
						"jdbc:mysql://localhost:3306/tc", "tc",
						"textbookcrossroads");
				Statement statement = connection.createStatement();
				String isbn=request.getParameter("isbn");
				String q3=" where isbn13='"+isbn+"' ";
				String title=request.getParameter("title");
				String q1=" title='"+title+"' ";
				String authors=request.getParameter("authors");
				String q2=" authors='"+authors+"' ";
				
				String query="update textbooks set "+q1+","+q2+q3;;
				statement.executeUpdate(query);
				statement.close();
				connection.close();
				//String[] author_array=authors.split(",");
//				Book book=bdao.getBook(new Isbn(isbn));				
//				book.setTitle(title);
//				for (String s:author_array)
//				{
//					if (!book.getAuthors().contains(s))
//
//						book.getAuthors().add(s);
//				}
//				bdao.updateBook(book);
				//request.setAttribute("isbn", isbn);
				request.setAttribute("afterupdate", bdao.getBook(new Isbn(isbn)));
				return mapping.findForward("success_post");
			}
			
			return mapping.findForward("failure");
		}
		catch (Exception e)
		{
			
			return mapping.findForward("failure");
		}
		
	}

}
